package qt

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	logic2 "iot-base/auth/api/logic"
	"iot-base/auth/common"
	Log "iot-base/auth/logger"
	types2 "iot-base/auth/types"
	"iot-base/common/ctrltype"
)

func GetPresets(data []byte) (interface{}, int) {
	var req types2.ReqGetPresets
	if err := json.Unmarshal(data, &req); err != nil {
		return "", types2.ParamsError
	}
	list, err := logic2.NewPresetLogic().GetPresets(req.ThingId)
	if err != nil {
		return nil, types2.Fail
	}
	return gin.H{"list": list}, types2.Success
}

func SetPresets(data []byte) (interface{}, int) {
	var req types2.ReqSetPreset
	if err := json.Unmarshal(data, &req); err != nil {
		return "", types2.ParamsError
	}
	profileToken, _ := getProfileToken(req.ThingId)
	if profileToken == "" {
		return nil, types2.ParamsError
	}
	req.ProfileToken = profileToken

	params := map[string]interface{}{
		"ProfileToken": req.ProfileToken,
		"PresetName":   req.PresetName,
		"PresetToken":  req.PresetToken,
	}
	var cmd ctrltype.CtrlCmd
	cmd.ID = types2.SetPreset
	cmd.ThingID = req.ThingId
	cmd.Params = params
	result, err := common.CtrlResp(&cmd)
	// test
	//var err error
	//var result interface{}
	//result = 123
	if result != nil && err == nil {
		err = logic2.NewPresetLogic().SetPreset(req)
		if err != nil {
			Log.Log.Errorf("[qt] logic.NewPresetLogic().SetPreset err:=%v", err)
		}
		return gin.H{}, types2.Success
	} else {
		Log.Log.Errorf("[qt] GotoPreset err:=%v", err)
		return nil, types2.Fail
	}
}

func GoToPresets(data []byte) (interface{}, int) {
	var req types2.ReqGotoPreset
	if err := json.Unmarshal(data, &req); err != nil {
		return "", types2.ParamsError
	}
	profileToken, _ := getProfileToken(req.ThingId)
	if profileToken == "" {
		return nil, types2.ParamsError
	}
	req.ProfileToken = profileToken
	params := map[string]interface{}{
		"ProfileToken": req.ProfileToken,
		"PresetToken":  req.PresetToken,
	}
	//fmt.Println("ProfileToken",req.ProfileToken)
	var cmd ctrltype.CtrlCmd
	cmd.ID = types2.GotoPreset
	cmd.ThingID = req.ThingId
	cmd.Params = params
	result, err := common.CtrlResp(&cmd)
	if result != nil && err == nil {
		return result, types2.Success
	} else {
		Log.Log.Errorf("[qt] GotoPreset err:=%v", err)
		return nil, types2.Fail
	}
}
